package com.suny.juc;

import java.util.concurrent.Semaphore;

/**
 * 限制访问资源的线程数量 当达到指定数量线程后, 其他线程阻塞 当释放某个线程后, 将会从阻塞线程中选出一个继续运行
 * @author sunny
 * @date 2019/3/6
 */
public class SemaphoreTest {
    static class Parking {
        private Semaphore semaphore;

        public Parking(int count) {
            this.semaphore = new Semaphore(count);
        }

        public void park() {
            try {
                //获取信号量
                semaphore.acquire();
                long time = (long) (Math.random() * 10);
                System.out.println(Thread.currentThread().getName() + " 进入停车场, 停车: " + time + " 秒...");
                Thread.sleep(time);
                System.out.println(Thread.currentThread().getName() + " 开出停车场...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }
    }

    static class Car extends Thread {

        Parking parking;

        public Car(Parking parking) {
            this.parking = parking;
        }

        @Override
        public void run() {
            parking.park();
        }
    }

    public static void main(String[] args) {
        Parking parking = new Parking(3);
        for (int i = 0; i < 5; i++) {
            new Car(parking).start();
        }
    }
}
